﻿//--------------------------------------------------------------------------
// <copyright file="Ioes.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <summary>Ioes</summary>
//--------------------------------------------------------------------------
namespace MS.Msn.MediaSolutions.Common
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;

    /// <summary>
    /// Ioes
    /// </summary>
    public static class Ioes
    {
        /// <summary>
        /// auto create a dir (path)
        /// </summary>
        /// <param name="path">path</param>
        public static void ReachDir(string path)
        {
            if (!Directory.Exists(path))
            {
                string rut = Path.GetPathRoot(path);
                List<string> paths = new List<string>();

                paths.Add(path);
                while (!path.Equals(rut))
                {
                    path = Directory.GetParent(path).FullName;
                    paths.Add(path);
                }

                for (int i = paths.Count - 1; i >= 0; i--)
                {
                    if (!Directory.Exists(paths[i]))
                    {
                        Directory.CreateDirectory(paths[i]);
                    }
                }
            }
        }

        /// <summary>
        /// get a unique file name
        /// </summary>
        /// <param name="rootPath">root path</param>
        /// <param name="tempPath">temporary path</param>
        /// <param name="fileName">source file name</param>
        /// <returns>unique file name</returns>
        public static string GetUniqueFileName(string rootPath, string tempPath, string fileName)
        {
            if (string.IsNullOrEmpty(tempPath))
            {
                tempPath = string.Empty;
            }

            string fnam = Guid.NewGuid().ToString("N", Apps.DefaultCulture) + Path.GetExtension(fileName);
            string rtval = Path.Combine(rootPath, tempPath);

            ReachDir(rtval);

            rtval = Path.Combine(rtval, fnam);

            return rtval;
        }
    }
}
